package com.action.impl;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Properties;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.context.annotation.Scope;

import com.utils.Constants;
import com.utils.HttpPostUtil;
import com.utils.LoaderFileUtil;
import com.utils.UtilsFile;
import com.utils.UtilsProperties;

@Scope("prototype")
public class TaobaoAction extends BaseAction{
	public String oauth2() {
		String code = getRequest().getParameter("code");
		redirectPage = getRequest().getParameter("state").split("$")[0];
		List <NameValuePair> params = LoaderFileUtil.loadTBOauth("taobao_app.properties");  		
	    params.add(new BasicNameValuePair("code", code));   
	    String uri = "https://oauth.taobao.com/token";
	    String accessToken = null;
	    String nick = "";
	    String nick_db = "";
	    String result = HttpPostUtil.doPost(uri, params);
	    String login_user = "nick";
	    if(result!=null){
	    	try {
				JSONObject jsonObj = new JSONObject(result);
				accessToken = jsonObj.getString("access_token");
				nick = jsonObj.getString("taobao_user_nick");
				
				Properties prop = UtilsProperties.loadPropertiesByFile(Constants.APP_CONFIGFILE_PATH + "session");
				if(prop != null && prop.containsKey(login_user)){
					nick_db = ((String) prop.get(login_user)).split(",")[0];
					if(!nick_db.equals(nick)){
						addFieldError("oauth", "授权失败!用户不同!");
					}else{
						UtilsFile.LogToFile2(new File(Constants.APP_CONFIGFILE_PATH + "session"), login_user + "=" + nick + "," + accessToken, false);
						addFieldError("oauth", "success!");
					}
				}else{
					UtilsFile.LogToFile2(new File(Constants.APP_CONFIGFILE_PATH + "session"), login_user + "=" + nick + "," + accessToken, true);
					addFieldError("oauth", "success!");
				}
				
			} catch (JSONException e) {
				return ERROR;
			} catch (IOException e) {
				e.printStackTrace();
			}
	    }
	    return SUCCESS;
	}

	public void oauth1() throws IOException {
		Properties props = UtilsProperties.loadPropertiesByCurrentThread("taobao_app.properties");
		String oauthUrl = "https://oauth.taobao.com/authorize?client_id="+props.get("client_id")+"&view=web&response_type=code&scope=item&redirect_uri="
				+props.getProperty("redirect_uri");
		
		String login_user = "nick";
		Properties prop = UtilsProperties.loadPropertiesByFile(Constants.APP_CONFIGFILE_PATH + "session");
		String nick = "";
		if(prop != null && prop.containsKey(login_user)){
			nick = ((String) prop.get(login_user)).split(",")[0];
			oauthUrl = oauthUrl + "&&" + nick;
		}
		getResponse().getWriter().write(oauthUrl);
	}
}




